import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/acl';
import type { RouteRecordRaw } from 'vue-router';
//引入路由器
import router from '@/router'
import { cloneDeep } from 'lodash'

const filterallAsyncRoutes = (allAsyncRoutes: RouteRecordRaw[], routeNames: string[]) => {
  let result = allAsyncRoutes.filter(route => {
    if (route.children && route.children.length) {
      route.children = filterallAsyncRoutes(route.children as RouteRecordRaw[], routeNames);
    }
    return routeNames.includes(route.name as string);
  })
  return result
}

const addRoutes = (allRoutes: RouteRecordRaw[]) => {
  allRoutes.forEach(route => {
    router.addRoute(route);
  })
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

  actions: {
    //账号与密码
    async login(username: string, password: string) {
      let result: any = await reqLogin({ username, password });
      // console.log(result);
      //持久化存储
      setToken(result.token);
      this.token = result.token;
    },
    //用户信息
    async getInfo() {
      let result: any = await reqUserInfo();
      // console.log(result);
      this.name = result.name;
      this.avatar = result.avatar;
      //侧面菜单栏
      const filterRoutes = filterallAsyncRoutes(cloneDeep(allAsyncRoutes), result.routes);
      const allRoutes = staticRoutes.concat(filterRoutes, anyRoute);
      this.menuRoutes = allRoutes;
      addRoutes(allRoutes);
    },

    //退出登录
    async reset() {
      await reqLogOut();
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
    },
  },
});
